package demo2_example;


import java.util.Arrays;
import java.util.Comparator;
//1
//重写compareTo方法
//该方法对类的侵入性比较强
//只能通过年龄的大小进行排序，若要根据年龄则要修改比较方法部分的代码
//实现Comparable接口，重写compareTo方法
public class Student implements Comparable<Student>{
    int age;
    String name;

    public Student(int age, String name) {
        this.age = age;
        this.name = name;
    }
    //重写toString方法
    @Override
    public String toString() {
        return name + ":" + age ;
    }
    //重写compaeTo方法
    @Override
    public int compareTo(Student o) {
        return this.age - o.age;
    }

    //重写一个冒泡排序用以实现sort+compareTo的作用
    //只要一个类实现了Comparable接口则均能被传入该方法
    public static void bubbleSort(Comparable [] comparable){
        for(int i = 0; i < comparable.length - 1; i++){
            for(int j = 0; j < comparable.length - 1 - i; j++){
                if(comparable[j].compareTo(comparable[j+1]) > 0){
                    Comparable tmp = comparable[j+1];
                    comparable[j+1] = comparable[j];
                    comparable[j] = tmp;
                }
            }
        }
    }

    public static void main1(String[] args) {
        Student [] stu = new Student[]{
                new Student(12,"zhangsan"),
                new Student(6,"lisi"),
                new Student(78,"wangwu")
        };
        //Arrays.sort(stu);
        System.out.println(Arrays.toString(stu));
        bubbleSort(stu);
        System.out.println(Arrays.toString(stu));
    }
}
//2
//比较器
//通过年龄进行比较
class AgeCompare implements Comparator<Student> {

    @Override
    public int compare(Student o1, Student o2) {
        return o1.age - o2.age;
    }
}

//通过姓名进行比较
class NameCompare implements Comparator<Student>{
//调用字符串的专用比较方法
    @Override
    public int compare(Student o1, Student o2) {
        return o1.name.compareTo(o2.name);
    }
}

class Test1{
    public static void main(String[] args) {
        Student stu1 = new Student(56,"zhouyi");
        Student stu2 = new Student(24,"zhoumo");
        AgeCompare ageCompare = new AgeCompare();
        System.out.println(ageCompare.compare(stu1, stu2));
        //还有一个姓名待实现
        NameCompare nameCompare = new NameCompare();
        System.out.println(nameCompare.compare(stu1, stu2));
    }
}

